package com.rop.znyx.acl.controller;

import com.rop.znyx.acl.service.RolePermissionService;
import com.rop.znyx.common.result.Result;
import com.rop.znyx.model.acl.Permission;
import com.rop.znyx.acl.service.PermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created with IntelliJ IDEA
 * User: Rop
 * Date: 2023/6/16
 * Time: 14:27
 * Description: 菜单管理
 */

@RestController
@RequestMapping("/admin/acl/permission")
@Api(tags = "菜单管理")
@RequiredArgsConstructor
 //跨域
public class PermissionAdminController {

    private final PermissionService permissionService;

    private final RolePermissionService rolePermissionService;

    @ApiOperation(value = "获取菜单")
    @GetMapping
    public Result<List<Permission>> index() {
        List<Permission> list = permissionService.queryAllMenu();
        return Result.ok(list);
    }

    @ApiOperation(value = "新增菜单")
    @PostMapping("save")
    public Result<Boolean> save(@RequestBody Permission permission) {
        boolean success = permissionService.save(permission);
        return success ? Result.ok() : Result.fail();
    }

    @ApiOperation(value = "修改菜单")
    @PutMapping("update")
    public Result<Boolean> updateById(@RequestBody Permission permission) {
        boolean success = permissionService.updateById(permission);
        return success ? Result.ok() : Result.fail();
    }

    @ApiOperation(value = "递归删除菜单")
    @DeleteMapping("remove/{id}")
    public Result<Boolean> remove(@PathVariable Long id) {
        boolean success = permissionService.removeChildById(id);
        return success ? Result.ok() : Result.fail();
    }

    /**
     * 获取所有角色拥有的权限数据
     *
     * @param id 角色id
     */
    @ApiOperation("根据角色获取菜单数据")
    @GetMapping("/toAssign/{id}")
    public Result<List<Permission>> toAssign(@PathVariable Long id) {
        List<Permission> roleMap = permissionService.findRoleByUserId(id);
        return Result.ok(roleMap);
    }

    /**
     * 给角色分配菜单
     */
    @ApiOperation("给角色分配菜单")
    @PostMapping("doAssign")
    public Result<Boolean> doAssign(@RequestParam Long roleId, @RequestParam Long[] permissionId) {
        boolean isSuccess = permissionService.doAssign(roleId, permissionId);
        return isSuccess ? Result.ok() : Result.fail();
    }
}
